package UserClientSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import UserGlobal.GlobalData;
public class Client {
    public Socket mSocket = new Socket();//客户端socket
    public Client(){}
    public Client(int port, int connecttime, int readwritetime) throws IOException {
        SocketAddress address = new InetSocketAddress(GlobalData.Serverip, port);//服务器地址
            if (!mSocket.isConnected()) {
                if (connecttime != 0) {
                    mSocket.connect(address, connecttime);//设置连接超时
                } else
                    mSocket.connect(address);
                if (readwritetime != 0)
                    mSocket.setSoTimeout(readwritetime);//设置读写超时
                mSocket.setKeepAlive(true);
            }
        }

    public void close(){
        try {
            mSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String receiveString() throws IOException {
        int len = receiveInt();
        String str = receive(len);
        return str;
    }
    private String receive(int len) {//len为字符串长度
        try {
            InputStream mInputStream = mSocket.getInputStream();
            byte[] bytelist = new byte[len];
            mInputStream.read(bytelist);
            String str = new String(bytelist);
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    public int receiveInt() throws IOException {
        String num = "";
        InputStream mInputStream = mSocket.getInputStream();
        byte[] bytelist = new byte[4];
        mInputStream.read(bytelist);
        int len = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (3 - i) * 8;
            len += (bytelist[i] & 0xFF) << shift;
        }
        return len;
    }
    public void sendString(String str) throws IOException {
        sendInt(str.getBytes().length);
        byte[] bytes = str.getBytes("utf-8");
        OutputStream mDataOutputStream = mSocket.getOutputStream();
        mDataOutputStream.write(bytes);
        mDataOutputStream.flush();
    }
    public void sendInt(int i) throws IOException {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) ((i) & 0xFF);
        OutputStream mDataOutputStream = mSocket.getOutputStream();
        mDataOutputStream.write(result);
        mDataOutputStream.flush();
    }
}